import { App, Body, Controller, Get, Post, Query } from "@midwayjs/core";
import { Application } from "../interface.js";
import { TbBookDto } from "../models/tbBooks.js";
import { Ok } from "../config/resUtil.js";

@Controller('/api/book')
export class BookController {
  @App('koa')
  app: Application;
  @Get('/list')
  async list(): Promise<any> {
    // var inert_result=await knex('tb_books').insert({title: 'Slaughterhouse Five'})
    var result1=await  this.app.db.select().table('tb_books')
    return result1;
  }
  @Post('/add')
  async add(@Body() body:TbBookDto): Promise<any> {
    if(!body?.title){
    return {success:false,message:'title 必填'}
    }
    var inert_result=await this.app.db('tb_books').insert(body).returning('id')
    return {success:true,message:inert_result};
  }

  @Post('/update')
  async update(@Body() body:TbBookDto): Promise<any> {
    if(!body?.id){
      return {success:false,message:'id 必填'}
    }
    var result=await this.app.db('tb_books').returning('id')
      .where('id',body?.id)
    .update(body)
    return {success:true,message:result};
  }

  @Get('/getbyid')
  async getbyid(@Query("id")id:number): Promise<any> {
    if(!id){
      return {success:false,message:'id 必填'}
    }
    var one=await this.app.db('tb_books')
      .where('id','=',id)
    .first()
    return Ok(one);
  }

  @Post('/getlist')
  async getlist(@Body()body:TbBookDto): Promise<any> {
    var query=this.app.db('tb_books').where(1,'=',1)
    if(body?.id){
      query.andWhere('id','=',body.id)
    }
    if(body?.title){
      query.andWhere('title','like',`${body.title}%`)
    }
    return Ok(await query);
  }
}
